package servlets.twitterServlets;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterSigninServlet extends HttpServlet {
    private static final long serialVersionUID = -6205814293093350242L;
	/** Consumer key for the API */
	private static String consumerKey = "VyV0m7JSUHWUr0d9Azgw";
	/** Consumer secret key for the API */
	private static String consumerSecret = "Q0W9Une2A1q61mNPq7rOGd2T15tmxSJulTBSmJkho";
	private ConfigurationBuilder configurationBuilder;
	
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String scope, idUser;
    	scope = request.getParameter("scope");
    	configurationBuilder = new ConfigurationBuilder();
		configurationBuilder.setDebugEnabled(true);
		configurationBuilder.setOAuthConsumerKey(consumerKey);
		configurationBuilder.setOAuthConsumerSecret(consumerSecret);
    	Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
    	request.getSession().setAttribute("twitter", twitter);
        try {
            StringBuffer callbackURL = request.getRequestURL();
            int index = callbackURL.lastIndexOf("/");
            switch (scope) {
			case "login":
				 callbackURL.replace(index, callbackURL.length(), "").append("/TWITTERLoginCallback");
				break;
			case "addSocial":
				idUser = request.getParameter("idUser");
				callbackURL.replace(index, callbackURL.length(), "").append("/TWITTERAddSocialCallback?idUser=" + idUser);
				break;
			default:
				break;
			}
           
            
            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());

        } catch (TwitterException e) {
        	request.getSession().removeAttribute("twitter");
            throw new ServletException(e);
        }

    }
}
